package com.srp.backend.controller;

import com.srp.backend.common.Result;
import com.srp.backend.entity.User;
import com.srp.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

//    添加用户信息
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.insertUser(user);
        }catch (Exception e) {
            if(e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            }
            else{
                return Result.error("系统错误");
            }
        }

        return Result.success();
    }

//    修改用户信息
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

//    删除用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success();
    }
//根据id查询用户
    @GetMapping("/selectById/{id}")
    public Result gerUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }
//模糊查询
    @GetMapping("/selectFuzzily")
    public Result getUserfuzzily(String username, String name) {
        List<User> userlist=userService.getUserfuzzily(username,name);
        return Result.success(userlist);
    }

//    多条件模糊分页查询
    @GetMapping("/selectByPage")
    public Result getUserByPage(@RequestParam Integer pagenum, @RequestParam Integer pagesize,
                                @RequestParam String username, @RequestParam String name) {
        Map<String,Object> result=new HashMap<>();
        List<User> userList=userService.getUserByPage(pagenum,pagesize,username,name);
        Integer total=userService.getUserCount(username,name);
        result.put("userList",userList);
        result.put("total",total);
        return Result.success(result);
    }
}
